using UnityEngine;
using System.Collections;
using System.IO;

/**
 * Script of file writing and reading.
 * The purpose of this class is to read and write a replay file.
 * @author Benjamin Bruneau
 */
public class StreamWriterScript : MonoBehaviour 
{
	private const string REPLAY_MODE_NAME = "ReplayMode"; // Replay Mode GameObject's name
	private const string SAVE_URL = "replay.replay"; // Path for replay file
	
	private GameObject _replayMode; // Replay mode GameObject
	
	public GameObject _dataContainer; // Data container GameObject
	
	public StreamWriter _streamWriter; // Stream writer (IO)
	
	public string _lastLine = ""; // Last line
	public string _save = ""; // Total saved informations

	
	/**
	 * Called on initialization.
	 * @return void
	 */
	void Start ()
	{
		
		//Initialized because this object moves through scenes
		_replayMode = GameObject.Find (REPLAY_MODE_NAME);
		
		// If not in replay mode
		if(!_replayMode.GetComponent<ReplayModeScript>()._replayMode)
		{
			// New stream
			_streamWriter = new StreamWriter(SAVE_URL); 
		}
	}
	
	/**
	 * Called on destruction.
	 * @return void
	 */
	void OnDestroy()
	{
		// If stream was opened
		if(_streamWriter != null)
		{
			// Write, flush, close
			string[] splitSave =_save.Split('#');
			foreach (string line in splitSave) 
			{ 
				_streamWriter.WriteLine(line);
			}
		_streamWriter.Close(); 
		}
	}
	
	/**
	 * Writes line.
	 * @param string
	 * @return void
	 */
	public void write(string pLineToWrite)
	{
		// Get time
		pLineToWrite = pLineToWrite + _dataContainer.GetComponent<TimeScript>().getTime();
		
		// Add line to global save
		if(!_save.Equals(""))
		{
			_save = _save + "#" + pLineToWrite;
		} else {
				_save = pLineToWrite;
		}
	}
	
	/**
	 * Read in file to get replay.
	 * @return ArrayList
	 */
	public ArrayList read()
	{
		ArrayList sequence = new ArrayList();
		
		// Open stream reader
 		StreamReader streamReader = new StreamReader(SAVE_URL); 
		
		// Read line
		string line = streamReader.ReadLine(); 
		while (line != null) 
		{ 
			// Split and format it
			string[] splitLine = line.Split(';');
			sequence.Add(new ArrayList(){splitLine[0],float.Parse(splitLine[1]), float.Parse(splitLine[2]), float.Parse(splitLine[3]), float.Parse(splitLine[4]), float.Parse(splitLine[5]), float.Parse(splitLine[6]), float.Parse(splitLine[7]), float.Parse(splitLine[8])});
			
			// Read line
			line = streamReader.ReadLine(); 
		} 
		
		// Close stream reader
		streamReader.Close(); 
		
		return sequence;
	}	
}
